package cn.xxlucky.xssdk01.demo.service.impl;

import cn.xxlucky.xssdk01.demo.service.IXfAIService;
import cn.xxlucky.xssdk01.pojo.ApiRequest;
import cn.xxlucky.xssdk01.pojo.ApiResponse;
import cn.xxlucky.xssdk01.util.HttpClientUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter;

import java.io.IOException;
import java.util.List;

@Slf4j
@Service
public class XfAiServiceImpl implements IXfAIService {
    @Value("${xf.url}")
    private String apiUrl;

    @Value("${xf.apiPwd}")
    private String apiToken;

    @Override
    public ApiResponse sendRequest(ApiRequest apiRequest) {
        try {
            // 将请求对象转换为JSON字符串
            String jsonRequest = JSON.toJSONString(apiRequest);

            // 添加Authorization头
            String responseJson = HttpClientUtil.doPostJsonWithHeader(apiUrl, jsonRequest, apiToken);


            // 将返回的JSON字符串转换为响应对象
            return JSON.parseObject(responseJson, ApiResponse.class);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public void sendRequest(ResponseBodyEmitter emitter, ApiRequest apiRequest) {
        try {
            // 设置流式请求
            apiRequest.setStream(true);

            // 将请求对象转换为JSON字符串
            String jsonRequest = JSON.toJSONString(apiRequest);


            // 添加Authorization头并逐步返回流式响应
            HttpClientUtil.doPostStreamWithHeader(apiUrl, jsonRequest, apiToken, line -> {
                try {
                    if(line.length()>5){
                        log.debug("讯飞返回数据："+line);
                        // 因为返回的数据是 "data: {xxx:xxx}" 前面的data: 不是标准的json格式
                        line =  line.substring(6);
                        //结束会发一个data: [DONE]过来 不能再解析了
                        if(!("[DONE]".equals(line))){
                            ApiResponse apiResponse = JSON.parseObject(line, ApiResponse.class);
                            List<ApiResponse.Choice> choices = apiResponse.getChoices();
                            for (ApiResponse.Choice choice : choices) {
                                // 只发送正文部分 返回例子：data: {\"code\":0,\"message\":\"Success\",\"sid\":\"cha000c6eee@dx193bf56f3bbb8f3532\",\"id\":\"cha000c6eee@dx193bf56f3bbb8f3532\",\"created\":1734081967,\"choices\":[{\"delta\":{\"role\":\"assistant\",\"content\":\"\"},\"index\":0}],\"usage\":{\"prompt_tokens\":78,\"completion_tokens\":0,\"total_tokens\":78}}
                                String content = choice.getDelta().getContent();

                                // 返回的数据类型 要告诉浏览器，我这是个流式请求的，  预防乱码设置 UTF8
                                MediaType mediaType = new MediaType("text", "event-stream", java.nio.charset.StandardCharsets.UTF_8);

                                // 逐行发送数据  要保证统一的格式，否则流式请求发不出去
                                emitter.send( "data: " + content + "\n\n",  mediaType);
                            }
                        }
                    }
                } catch (IOException e) {
                    emitter.completeWithError(e);
                }
            });

            // 完成流式响应
            emitter.complete();
        } catch (Exception e) {
            emitter.completeWithError(e);
        }
    }



}
